<template>
  <div class="order_form">
    <el-form
      ref="orderForm"
      :model="orderForm"
      :rules="ruleForm"
    >
      <!-- 乘机人 -->
      <div class="passenger">
        <div class="order_title">乘机人</div>
        <div class="passenger_content">
          <div
            v-for="(item,index) in orderForm.users"
            :key="index"
            class="user_item_wrap"
          >
            <span
              class="remove_user"
              v-if="index!==0"
              @click="removeUser(index)"
            >-</span>
            <el-form-item
              label="乘机人"
              :prop="'users.'+index+'.username'"
              :rules="{
      required: true, message: '乘机人不能为空', trigger: 'blur'
    }"
            >
              <el-input v-model="item.username"></el-input>
            </el-form-item>
            <el-form-item
              label="证件类型"
              :prop="'users.'+index+'.id'"
              :rules="{
      required: true, message: '身份证不能为空', trigger: 'blur'
    }"
            >
              <el-input
                placeholder="请输入内容"
                class="input-with-select"
                v-model="item.id"
              >
                <el-select
                  slot="prepend"
                  placeholder="请选择"
                  class="id_select"
                  value="1"
                >
                  <el-option
                    label="身份证"
                    value="1"
                  ></el-option>

                </el-select>
              </el-input>
            </el-form-item>
          </div>
          <div class="users_btn">
            <el-button
              type="primary"
              @click="addPassenger"
            >添加乘机人</el-button>
          </div>
        </div>
      </div>

      <!-- 虚线 -->
      <div class="dashed_line"></div>

      <!-- 保险 -->
      <div class="insurances">
        <div class="order_title">保险</div>
        <div class="insurances_content">
          <div
            class="insurances_item"
            v-for="item in airSeatInfo.insurances"
            :key="item.id"
          >
            <el-checkbox
              @change="insurancesChange(item.id)"
              :label="`${item.type} : ￥${item.price}份/x1 最高赔付 ${item.compensation}`"
              border
            ></el-checkbox>
          </div>
        </div>

      </div>

      <div class="dashed_line"></div>

      <!-- 联系人 -->
      <div class="contact_wrap">
        <div class="order_title">联系人</div>
        <div class="contact_content">
          <el-form-item
            class="contact_item"
            label="姓名"
            prop="contactName"
          >
            <el-input v-model="orderForm.contactName"></el-input>
          </el-form-item>
          <el-form-item
            class="contact_item"
            label="手机"
            prop="contactPhone"
          >
            <el-input v-model="orderForm.contactPhone">
              <template slot="append"><span @click="sendCaptcha">发送验证码</span></template>
            </el-input>
          </el-form-item>
          <el-form-item
            class="contact_item"
            label="验证码"
            prop="captcha"
          >
            <el-input v-model="orderForm.captcha"></el-input>
          </el-form-item>
        </div>
        <div class="submit_wrap">
          <el-button
            type="warning"
            @click="submitForm"
          >提交订单</el-button>
        </div>
      </div>
    </el-form>

  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  data() {
    return {
      // 表单
      orderForm: {
        users: [{ username: "1", id: "2" }],
        // 保险 [保险的id 即可 ]  不用做什么校验
        insurances: [],
        // 联系人
        contactName: "1",
        // 联系人的电话
        contactPhone: "2",
        // 手机验证码 后台约定 手机验证码的值要写 6个 0
        captcha: "000000",
        // 座位id
        seat_xid: this.$route.query.seat_xid,
        // 航班id
        air: this.$route.query.id,
      },
      // 验证规则
      ruleForm: {
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入手机", trigger: "blur" },
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      // 机票-座位详情
      airSeatInfo: {},
      // airSeatInfo.insurances
    };
  },
  async mounted() {
    // /airs/1?seat_xid=f3f796c5990cd570ef20e406ab2e541f
    const { id, seat_xid } = this.$route.query;
    this.airSeatInfo = await this.$axios.get("/airs/" + id, {
      params: { seat_xid: seat_xid },
    });
    console.log(this.airSeatInfo);
  },
  methods: {
    // 点击添加乘机人
    addPassenger() {
      this.orderForm.users.push({ username: "1", id: "2" });
    },
    // 点击删除 乘机人
    removeUser(index) {
      this.orderForm.users.splice(index, 1);
    },
    // 切换选中 保险
    insurancesChange(id) {
      const index = this.orderForm.insurances.indexOf(id);
      if (index === -1) {
        // 执行添加
        this.orderForm.insurances.push(id);
      } else {
        // 执行删除
        this.orderForm.insurances.splice(index, 1);
      }
    },
    // 点击发送验证码
    sendCaptcha() {
      // 1 验证一下手机号码是否合法 利用element表单功能做验证
      this.$refs.orderForm.validateField("contactPhone", async (errMessage) => {
        // 是否合法 不合法就是一段错误信息 合法就是空字符串
        if (!errMessage) {
          // 合法
          // 2 合法 再发送请求来获取手机验证码
          const res = await this.$axios.post("/captchas", {
            tel: this.orderForm.contactPhone,
          });
          // console.log(res);
          this.$message.success("发送验证码成功");
        }
      });
    },
    // 提交订单
    submitForm() {
      /* 
      1 是否有token
        1 没有token 跳转回登录页面
        2 登录成功了再跳回来 
      2 有token
        1 对表单做合法性验证
        2 去拼接数据 发送请求 完成 提交订单即可 
       */
      const { token } = this.userInfo;

      if (!token) {
        // console.log("跳转到登录页面");

        this.$message.warning("您还没有登录");
        setTimeout(() => {
          // 在跳转的同时 带上当前的url
          // 让它知道在登录成功之后跳回到哪里
          const { fullPath } = this.$route;
          // 需要先将它转为json格式 再传递 否则 浏览器会做转码处理!!!

          this.$router.push({
            path: "/user/login",
            query: { fullPath },
          });
        }, 1500);

        return;
      }

      //  2 对整个表单做合法性的校验
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          //  验证通过
          console.log("验证通过");
          // airorders
          const res = await this.$axios.post("/airorders", this.orderForm, {
            headers: {
              // jwt json web token
              Authorization: "bearer " + token,
            },
          });
          console.log(res);

        this.$message.success("订单提交成功");
        setTimeout(() => {
          this.$router.push({path:"/air/pay",query:{id:res.data.id}});
        }, 1500);


        } else {
          console.log("不通过");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.id_select {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.user_item_wrap {
  position: relative;
}
.remove_user {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: #dddddd;
  color: #fff;
  right: -30px;
  top: 55%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.dashed_line {
  border-bottom: 1px dashed #000;
  margin: 20px 0;
}
.insurances {
  .insurances_content {
    .insurances_item {
      padding: 10px 0;
    }
  }
}
.contact_wrap {
  .contact_content {
    padding-right: 200px;
    .contact_item {
      display: flex;
      // 右对齐
      justify-content: flex-end;
    }
    .contact_item:nth-child(odd) {
      /deep/ input {
        width: 312px;
      }
    }
  }
}
</style>